let db = require("../db/index");
 // 通用查询函数
const queryDatabase = (sql, res) => {
    db.query(sql, (err, results) => {
        
        if (err) {
            console.error("数据库查询出错:", err);
            return res.status(500).send("数据库查询出错: " + err.message);
        }
        res.send(results[0]); // 通常db.query返回的结果是一个数组，其中第一个元素是结果集
    });
};
exports.buildall = (req, res) => {
    const sql = "SELECT BuildingName FROM building;";
    // queryDatabase(sql, res);
    db.query(sql, [], (err, data) => {
        if (err) {
            console.log("出错了", err);
            return res.send("错误" + err.message);
        }
        res.send(data);
    });
};
//查询每个楼栋的楼栋数
exports.buildCount = (req, res) => {
    const sql = `SELECT COUNT(*) AS buildCount from building, unit,floor,room where building.BuildingID=unit.BuildingID AND unit.UnitID=floor.UnitID and floor.FloorID=room.FloorID AND building.BuildingName = '${req.query.build}';`;

    queryDatabase(sql, res);
};
//查询每个楼栋的房间数
exports.roomCount = (req, res) => {
    const sql = `SELECT COUNT(*) as inRoom  from building, unit,floor,room where building.BuildingID=unit.BuildingID AND unit.UnitID=floor.UnitID and floor.FloorID=room.FloorID AND building.BuildingName = '${req.query.build}' and room.Status='已入住';`;

    queryDatabase(sql, res);
};